package project.sample.io;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class HttpServerContainer {


    private ThreadPoolExecutor bossGroup;

    private ThreadPoolExecutor workerGroup;

    private ServerSocket serverSocket;

    private int port;

    public HttpServerContainer(int port) {
        this.port = port;
        init();
    }

    public void init() {
        workerGroup = new ThreadPoolExecutor(20, 100, Long.MAX_VALUE, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(200), new ThreadPoolExecutor.AbortPolicy());
        bossGroup = new ThreadPoolExecutor(5, 20, Long.MAX_VALUE, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(20), new ThreadPoolExecutor.AbortPolicy());
    }

    public void open() {
        try {
            serverSocket = new ServerSocket(port);
            checkActive();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkActive() {
        while (bossGroup.getActiveCount() < 5) {
            listen();
        }
    }

    private void listen() {
        bossGroup.submit(() -> {
            try {
                Socket socket = serverSocket.accept();
                workerGroup.submit(new WorkerThread(socket));
            } finally {
                checkActive();
            }
            return null;
        });
    }

    public static void main(String[] args) {
        new HttpServerContainer(8888).open();
    }


}
